package org.jeecg.modules.factor.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.api.DTO.EmissionFactorUnitDTO;
import org.jeecg.modules.api.VO.EmissionFactorQueryUnitVO;
import org.jeecg.modules.api.VO.EmissionFactorUnitVO;
import org.jeecg.modules.api.entity.CyEmissionFactorData;
import org.jeecg.modules.api.entity.CyEmissionUnit;
import org.jeecg.modules.api.entity.CyEmissionUnitConvert;
import org.jeecg.modules.factor.mapper.CyEmissionUnitConvertMapper;
import org.jeecg.modules.factor.mapper.CyEmissionUnitMapper;
import org.jeecg.modules.factor.request.SynchronousUnitRequest;
import org.jeecg.modules.factor.service.ICyEmissionFactorDataService;
import org.jeecg.modules.factor.service.ICyEmissionUnitService;
import org.jeecg.modules.unitGroup.entity.CyFactorUnitGroup;
import org.jeecg.modules.unitGroup.service.ICyFactorUnitGroupService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 碳排因子单位
 * @Author: jeecg-boot
 * @Date:   2024-11-01
 * @Version: V1.0
 */
@Service
public class CyEmissionUnitServiceImpl extends ServiceImpl<CyEmissionUnitMapper, CyEmissionUnit> implements ICyEmissionUnitService {

    @Autowired
    private CyEmissionUnitMapper cyEmissionUnitMapper;

    @Autowired
    private CyEmissionUnitConvertMapper cyEmissionUnitConvertMapper;

    /**
     *  单位分组service层
     */
    @Autowired
    private ICyFactorUnitGroupService cyFactorUnitGroupService;

    /**
     *  碳排因子数据详情Service层
     */
    @Autowired
    private ICyEmissionFactorDataService cyEmissionFactorDataService;    //碳排因子数据详情Service层



    /**
     *  新增
     */
    @Override
    @Transactional
    public Result<String> addUnit(EmissionFactorUnitDTO emissionFactorUnitDTO) {
        // 查询当前的碳排因子单位是否已经存在（根据单位分组id及单位名称来判断的）
        CyEmissionUnit checkUnit = cyEmissionUnitMapper.checkSameUnit(emissionFactorUnitDTO.getUnitCode(),emissionFactorUnitDTO.getParentId());
        if(checkUnit !=null){
            return Result.error("该单位已存在,不可重复添加");
        }else{
            CyEmissionUnit cyEmissionUnit = new CyEmissionUnit();      //构造单位对象
            cyEmissionUnit.setParentId(emissionFactorUnitDTO.getParentId());   //关联单位分组id
            cyEmissionUnit.setParentName(emissionFactorUnitDTO.getParentName());  //关联单位分组名称
            cyEmissionUnit.setUnitCode(emissionFactorUnitDTO.getUnitCode());    //设置单位
            cyEmissionUnitMapper.addUnit(cyEmissionUnit);   //插入单位对象


            //如果新增单位时，没有添加单位转换对象，则不进行插入
            if(emissionFactorUnitDTO.getUnitConvertList() !=null && emissionFactorUnitDTO.getUnitConvertList().size()>0){
                List<CyEmissionUnitConvert> unitConvertList = emissionFactorUnitDTO.getUnitConvertList();      //获取所有的单位换算对象
                for (CyEmissionUnitConvert cyEmissionUnitConvert : unitConvertList) {
                    //如果为正向单位转换对象，则需设置源单位id
                    if(cyEmissionUnitConvert.getType().equals("1")){
                        cyEmissionUnitConvert.setUnitId(cyEmissionUnit.getId());     //关联单位的id(同时也是source_unit_id)
                        //如果为反向单位转换对象，则需设置目标单位id
                    }else if(cyEmissionUnitConvert.getType().equals("2")){
                        cyEmissionUnitConvert.setTargetUnitId(cyEmissionUnit.getId());     //关联目标单位的id
                    }else{
                        return Result.error("单位转换对象类型错误");
                    }
                }
                cyEmissionUnitConvertMapper.BatchInsert(unitConvertList);     //批量插入单位换算对象
            }
            return Result.ok("新增成功");
        }
    }

    /**
     *  删除
     */
    @Override
    @Transactional
    public void deleteById(String id) {
        cyEmissionUnitMapper.deleteById(id);    //删除单位
        //删除单位相关联的换算对象
        cyEmissionUnitConvertMapper.deleteByUnitId(id);      //删除正向转换对象
        cyEmissionUnitConvertMapper.deleteByTargetUnitId(id);  //删除反向转换对象
    }

    /**
     *  详情
     */
    @Override
    public EmissionFactorUnitVO queryById(String id) {
        //查询单位对象
        CyEmissionUnit cyEmissionUnit = cyEmissionUnitMapper.selectById(id);
        //查询出包含的正反单位换算对象
        List<CyEmissionUnitConvert> UnitConvertList = cyEmissionUnitConvertMapper.selectAllConvert(id);
        EmissionFactorUnitVO  emissionFactorUnitVO = new EmissionFactorUnitVO();
        emissionFactorUnitVO.setCyEmissionUnit(cyEmissionUnit);
        emissionFactorUnitVO.setCyEmissionUnitConvert(UnitConvertList);
        return emissionFactorUnitVO;
    }

    @Override
    @Transactional
    public void editUnit(EmissionFactorUnitDTO emissionFactorUnitDTO) {

        CyEmissionUnit cyEmissionUnit = new CyEmissionUnit();
        BeanUtils.copyProperties(emissionFactorUnitDTO, cyEmissionUnit);
        //更新单位信息
        cyEmissionUnitMapper.updateById(cyEmissionUnit);

        // 不确定是否有新增或删除的转换对象，所以对单位换算对象进行先删除后插入操作
        cyEmissionUnitConvertMapper.deleteAllConvert(cyEmissionUnit.getId());


        //如果没有单位转换对象，则不进行插入
        if(emissionFactorUnitDTO.getUnitConvertList() != null && emissionFactorUnitDTO.getUnitConvertList().size()>0){
            List<CyEmissionUnitConvert> unitConvertList = emissionFactorUnitDTO.getUnitConvertList();
            for (CyEmissionUnitConvert cyEmissionUnitConvert : unitConvertList) {
                //如果为正向单位转换对象，则需设置源单位id
                if(cyEmissionUnitConvert.getType().equals("1")){
                    //如果传递过来的转换对象中有源单位id，则代表之前有该转换对象且编辑时没有删除该转换对象，不用重新设置id
                    if(cyEmissionUnitConvert.getUnitId()!=null && cyEmissionUnitConvert.getUnitId()!="" ){

                    }else{
                        cyEmissionUnitConvert.setUnitId(cyEmissionUnit.getId());     //关联单位的id(同时也是source_unit_id)
                    }
                }else if(cyEmissionUnitConvert.getType().equals("2")){
                    //如果传递过来的转换对象中有目标单位id，则代表之前有该转换对象且编辑时没有删除该转换对象，不用重新设置id
                    if(cyEmissionUnitConvert.getTargetUnitId()!=null && cyEmissionUnitConvert.getTargetUnitId()!=""){

                    }else{
                        cyEmissionUnitConvert.setTargetUnitId(cyEmissionUnit.getId());     //关联目标单位的id
                    }
                }else{
                    //转换类型识别错误
                    return;
                }
            }
            cyEmissionUnitConvertMapper.BatchInsert(unitConvertList);     //批量插入单位换算对象
        }
    }

    @Override
    public IPage<EmissionFactorQueryUnitVO> queryPageList(CyEmissionUnit cyEmissionUnit, Integer pageNo, Integer pageSize) {
        //构造分页对象
        Page<EmissionFactorQueryUnitVO> page = new Page<EmissionFactorQueryUnitVO>(pageNo, pageSize);
        //查询出碳排因子单位对象
        IPage<EmissionFactorQueryUnitVO> emissionFactorQueryVOIPage = cyEmissionUnitMapper.queryPageList(page, cyEmissionUnit);
        //获取到查询到的记录
        List<EmissionFactorQueryUnitVO> records = emissionFactorQueryVOIPage.getRecords();

        for (EmissionFactorQueryUnitVO emissionFactorQueryUnitVO : records) {
            //查询出碳排因子单位对应的正反换算对象，并封装在vo中
            List<CyEmissionUnitConvert> cyEmissionUnitConverts = cyEmissionUnitConvertMapper.selectAllConvert(emissionFactorQueryUnitVO.getId());
            emissionFactorQueryUnitVO.setCyEmissionUnitConvert(cyEmissionUnitConverts);
        }

        return emissionFactorQueryVOIPage;

    }

    /**
     *  查询所有单位
     */
    @Override
    public List<CyEmissionUnit> getAllUnit() {

        List<CyEmissionUnit> allUnit = cyEmissionUnitMapper.getAllUnit();

        return allUnit;
    }

    /**
     *  查询所有单位并分组
     */
    @Override
    public Map<String, List<CyEmissionUnit>> getAllUnitByGroup() {
        // 查询出所有单位
        List<CyEmissionUnit> allUnit = cyEmissionUnitMapper.getAllUnit();
        //　存储单位分组的map
        Map<String, List<CyEmissionUnit>> unitGroupMap = allUnit.stream().collect(Collectors.groupingBy(CyEmissionUnit::getParentName));

        return unitGroupMap;


    }

    /**
     * 通过excel导入
     * @return
     */
    @Override
    public Result<String> importEmissionUnit(List<CyEmissionUnit> unitList) {

        // 拿出所有的分组名称
        List<String> parentNameList = unitList.stream()
                .map(CyEmissionUnit::getParentName)
                .filter(StringUtils::isNotBlank) // 过滤掉为空的分组名称
                .distinct()  //去重
                .collect(Collectors.toList());

        // 批量新增分组的数组
        List<CyFactorUnitGroup> batchSaveGroupList = new ArrayList<>();

        // 循环所有的分组名称
        parentNameList.stream().forEach(item->{
            CyFactorUnitGroup cyFactorUnitGroup = new CyFactorUnitGroup();
            cyFactorUnitGroup.setGroupName(item);
            batchSaveGroupList.add(cyFactorUnitGroup);
        });
        // 批量保存
        cyFactorUnitGroupService.saveBatch(batchSaveGroupList);
        // 单位分组map（key为单位名称，value为id）
        Map<String, String> groupMap = batchSaveGroupList.stream().collect(Collectors.toMap(CyFactorUnitGroup::getGroupName, CyFactorUnitGroup::getId));

        // 批量新增分组的数组
        List<CyEmissionUnit> batchSaveUnitList = new ArrayList<>();

        // 循环单位列表
        unitList.stream().forEach(item->{
            if(StringUtils.isNotBlank(groupMap.get(item.getParentName()))){
                // 创建单位对象
                CyEmissionUnit cyEmissionUnit = new CyEmissionUnit();
                cyEmissionUnit.setParentName(item.getParentName());
                cyEmissionUnit.setParentId(groupMap.get(item.getParentName()));
                cyEmissionUnit.setUnitCode(item.getUnitCode());
                batchSaveUnitList.add(cyEmissionUnit);
            }
        });
        // 批量保存单位
        this.saveBatch(batchSaveUnitList);
        return Result.OK("导入成功");
    }

    @Override
    public Result<String> synchronousEmissionFactorUnit(List<SynchronousUnitRequest> convertList) {
        // 碳排因子数据详情集合
        List<CyEmissionFactorData> emissionFactorDataList = cyEmissionFactorDataService.list();
        // 查询出所有单位
        List<CyEmissionUnit> unitList = this.list();

        Map<String, String> unitMap = unitList.stream()
                .filter(unit -> StringUtils.isNotBlank(unit.getUnitCode())) // 防止空指针
                .collect(Collectors.toMap(
                        CyEmissionUnit::getUnitCode,  // 单位名称
                        CyEmissionUnit::getId,   // id
                        (existing, replacement) -> existing // 如果有重复 unitCode，保留第一个
                ));

        // 给对应的单位赋值id
        convertList.stream().forEach(convert->{
            if(StringUtils.isNoneBlank(unitMap.get(convert.getTargetUnitCode()))){
                convert.setTargetUnitId(unitMap.get(convert.getTargetUnitCode()));
            }
        });

        // 循环进行单位转换处理
        emissionFactorDataList.stream().forEach(item->{
            for (SynchronousUnitRequest synchronousUnitRequest : convertList) {
                if(item.getDenominatorUnit().equals(synchronousUnitRequest.getSourceUnitCode())){
                    item.setDenominatorUnit(synchronousUnitRequest.getTargetUnitCode());
                    item.setDenominatorUnitId(synchronousUnitRequest.getTargetUnitId());
                }
            }
        });
        //  批量更新
        cyEmissionFactorDataService.updateBatchById(emissionFactorDataList);
        return Result.OK("同步成功");
    }
}
